<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备组id" prop="groupId">
        <el-input
          v-model="queryParams.groupId"
          placeholder="请输入设备组id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主题id" prop="topicId">
        <el-input
          v-model="queryParams.topicId"
          placeholder="请输入主题id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.iot_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:alarm:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['iot:alarm:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:alarm:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:alarm:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="alarmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="alarmId"/>
      <el-table-column label="设备组id" align="center" prop="groupId"/>
      <el-table-column label="主题id" align="center" prop="topicId"/>
      <el-table-column label="主题" align="center">
        <template slot-scope="scope">
          {{ scope.row.groupName }}/{{ scope.row.topicName }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:alarm:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:alarm:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备告警对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item  label="告警主题" prop="selectedTopicValue">
          <el-cascader placeholder="请选择告警的主题" :show-all-levels="false"
                       v-model="form.selectedTopicValue"
                       :options="optionsTopic"
                       :disabled="updateWindow"
                       clearable
                       @change="handleChange"
          ></el-cascader>

        </el-form-item>
        <!--        <el-form-item label="设备组id" prop="groupId">-->
        <!--          <el-input v-model="form.groupId" placeholder="请输入设备组id" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="主题id" prop="topicId">-->
        <!--          <el-input v-model="form.topicId" placeholder="请输入主题id" />-->
        <!--        </el-form-item>-->
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.iot_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              :disabled="dict.value === '3'"

            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">告警联系人关联信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddIotMqttAlarmContacts">添加
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteIotMqttAlarmContacts">删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="iotMqttAlarmContactsList" :row-class-name="rowIotMqttAlarmContactsIndex"
                  @selection-change="handleIotMqttAlarmContactsSelectionChange" ref="iotMqttAlarmContacts"
        >
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" width="50"/>

          <el-table-column label="告警联系人" width="300">
            <template slot-scope="scope">

              <el-cascader :filterable="true"
                           placeholder="请选择告警通知人" :show-all-levels="false"
                           v-model="scope.row.selectedUserValue"
                           :disabled="disabled  || scope.row.status==='3'"
                           :options="optionsUser" clearable @change="handleUserChange"
              ></el-cascader>
            </template>
          </el-table-column>


          <el-table-column label="告警通知方式" width="150">
            <template slot-scope="scope">
              <el-select
                :disabled="scope.row.status==='3'"
                v-model="scope.row.notificationMethod" placeholder="请选择通知方式">
                <el-option
                  v-for="dict in dict.type.notification_method"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>

            </template>
            <!--            <template slot-scope="scope">-->
            <!--              <el-input v-model="scope.row.notificationMethod" placeholder="请输入告警通知方式" />-->
            <!--            </template>-->
          </el-table-column>
          <el-table-column label="状态" width="100">

            <template slot-scope="scope">
              <el-select
                :disabled="scope.row.status==='3'"
                v-model="scope.row.status" placeholder="请选择状态">
                <el-option
                  v-for="dict in dict.type.iot_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  :disabled="dict.value === '3'"
                ></el-option>
              </el-select>
              <!--              <el-select v-model="scope.row.status" placeholder="请选择是否启用 0 正常 1 停用 3 失效">-->
              <!--                <el-option label="请选择字典生成" value="" />-->
              <!--              </el-select>-->
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAlarm, getAlarm, delAlarm, addAlarm, updateAlarm, getTopic, getUser } from '@/api/iot/alarm'

export default {
  name: 'Alarm',
  dicts: ['iot_status', 'notification_method'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedIotMqttAlarmContacts: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备告警表格数据
      alarmList: [],
      // 告警联系人关联表格数据
      iotMqttAlarmContactsList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: null,
        topicId: null,
        status: null
      },
      // 表单参数
      form: {
        selectedTopicValue: [],
        status: '0',
        groupId: undefined,
        topicId: undefined

      },
      // 表单校验
      rules: {
        selectedTopicValue: [
          { required: true, message: '请选择主题', trigger: 'blur' }
        ]
      },
      updateWindow:false,
      disabled: true,
      optionsTopic: [],
      optionsUser: []

    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleUserChange(v) {
      this.resetOptionsUser()

    },
    resetOptionsUser() {
      this.optionsUser.forEach(item => {
        if (item.tag){
          item.disabled = false
        }
      })

      this.iotMqttAlarmContactsList.forEach(contacts => {
        this.optionsUser.forEach(item => {
          if (parseInt(contacts.selectedUserValue[0]) === parseInt(item.value)) {
            item.disabled = true
          }

          contacts.userId = parseInt(contacts.selectedUserValue[0])
        })
      })

    },
    handleChange(value) {
      if (value.length > 0) {

        this.disabled = false
        this.getUser(value[1], value[0])
        this.form.groupId = parseInt(value[0])
        this.form.topicId = parseInt(value[1])
      } else {
        this.disabled = true
      }

    },

    /** 查询设备告警列表 */
    getList() {
      this.loading = true
      listAlarm(this.queryParams).then(response => {
        this.alarmList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false

      this.reset()
    },
    // 表单重置
    reset() {

      this.form = {
        selectedTopicValue: [],
        alarmId: null,
        groupId: null,
        topicId: null,
        status: '0'
      }

      this.iotMqttAlarmContactsList = []

      this.resetForm('form')

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.alarmId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //    getUser(topicId, groupId) {
    //   this.loading = true
    //   getUser(topicId, groupId).then(response => {
    //     this.optionsUser = response.data
    //     console.log("getUser"+ this.optionsUser.length)
    //     this.loading = false
    //   })
    // },
    getUser(topicId, groupId) {
      return new Promise((resolve, reject) => {
        this.loading = true
        getUser(topicId, groupId).then(response => {
          this.optionsUser = response.data
          this.loading = false
          resolve() // 在异步操作完成后调用 resolve
        }).catch(error => {
          console.error('Error fetching user data:', error)
          this.loading = false
          reject(error) // 在发生错误时调用 reject
        })
      })
    },
    getTopic() {
      this.loading = true
      getTopic().then(response => {
        this.optionsTopic = response.data
        this.loading = false
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.updateWindow =false

      this.getTopic()

      this.reset()
      this.open = true
      this.title = '添加设备告警'
    },
    /** 修改按钮操作 */
    async  handleUpdate(row) {
      this.updateWindow =true
      this.getTopic()
      this.reset()
      const alarmId = row.alarmId || this.ids
        getAlarm(alarmId).then(async response => {
        this.form = response.data
        this.form.selectedTopicValue = [String(this.form.groupId), String(this.form.topicId)]
        this.disabled = false
        await this.getUser(this.form.topicId, this.form.groupId)
        this.iotMqttAlarmContactsList = response.data.iotMqttAlarmContactsList

        this.iotMqttAlarmContactsList.forEach(item => {
          if (item.status === '3') {
            this.optionsUser.push({
              value: String(item.userId),
              label: '[' + item.userName + '] [' + item.emial + '] [' + item.phonenumber + ']',
              disabled: true,
              children: null,
              tag :false,
            })
          }
          item.selectedUserValue = [String(item.userId)]
        })

        this.open = true
        this.title = '修改设备告警'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.iotMqttAlarmContactsList = this.iotMqttAlarmContactsList
          if (this.form.alarmId != null) {
            console.error(this.form)

            updateAlarm(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addAlarm(this.form).then(response => {
              console.error(this.form)

              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const alarmIds = row.alarmId || this.ids
      this.$modal.confirm('是否确认删除设备告警编号为"' + alarmIds + '"的数据项？').then(function() {
        return delAlarm(alarmIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 告警联系人关联序号 */
    rowIotMqttAlarmContactsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 告警联系人关联添加按钮操作 */
    handleAddIotMqttAlarmContacts() {
      let obj = {}
      obj.selectedUserValue = []
      obj.userId = ''
      obj.notificationMethod = '0'
      obj.status = '0'
      this.iotMqttAlarmContactsList.push(obj)
    },
    /** 告警联系人关联删除按钮操作 */
    handleDeleteIotMqttAlarmContacts() {
      if (this.checkedIotMqttAlarmContacts.length === 0) {
        this.$modal.msgError('请先选择要删除的告警联系人关联数据')
      } else {
        const iotMqttAlarmContactsList = this.iotMqttAlarmContactsList
        const checkedIotMqttAlarmContacts = this.checkedIotMqttAlarmContacts
        this.iotMqttAlarmContactsList = iotMqttAlarmContactsList.filter(function(item) {
          return checkedIotMqttAlarmContacts.indexOf(item.index) == -1
        })

        this.resetOptionsUser()
      }

      console.error( this.iotMqttAlarmContactsList)
    },
    /** 复选框选中数据 */
    handleIotMqttAlarmContactsSelectionChange(selection) {
      this.checkedIotMqttAlarmContacts = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/alarm/export', {
        ...this.queryParams
      }, `alarm_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
